export default class DynamicLoad {
    static isLoaded(tagName, property, path) {
        const tags = document.getElementsByTagName(tagName);
        if (tags.length === 0) {
            return false;
        } else {
            for (let i = 0; i < tags.length; i++) {
                if (tags[i].getAttribute(property) && tags[i].getAttribute(property).indexOf(path) !== -1) {
                    return true;
                }
            }
            return false;
        }
    }

    static loadJs(src) {
        return new Promise((resolve, reject) => {
            if (src === '') {
                reject('src参数不能为空');
            } else {
                // if (!this.isJsLoaded(src)) {
                if (!this.isLoaded('script', 'src', src)) {
                    const head = document.getElementsByTagName('head')[0];
                    const script = document.createElement('script');
                    script.setAttribute('type', 'text/javascript');
                    script.onload = () => {
                        resolve();
                    };
                    script.onerror = () => {
                        reject(`加载 ${src} 失败！`);
                    };
                    script.setAttribute('src', src);
                    head.appendChild(script);
                } else {
                    resolve();
                }
            }
        });
    }

    static loadCss(href) {
        if (href === '') {
            throw Error('href参数不能为空');
        } else {
            // if (!this.isCssLoaded(href)) {
            if (!this.isLoaded('link', 'href', href)) {
                const head = document.getElementsByTagName('head')[0];
                const link = document.createElement('link');
                link.setAttribute('rel', 'stylesheet');
                link.setAttribute('type', 'text/css');
                link.setAttribute('href', href);
                head.appendChild(link);
            }
        }
    }

    static loadResourceLink(href) {
        if (href === '') {
            throw Error('href参数不能为空');
        } else {
            // if (!this.isCssLoaded(href)) {
            if (!this.isLoaded('link', 'href', href)) {
                const head = document.getElementsByTagName('head')[0];
                const link = document.createElement('link');
                link.setAttribute('rel', 'resource');
                link.setAttribute('type', 'application/l10n');
                link.setAttribute('href', href);
                head.appendChild(link);
            }
        }
    }
}
